﻿using AdminBase.Interface;
using AdminBase.Model;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace AdminBase.Service
{
    /// <summary>
    /// 对称加密的token
    /// </summary>
    public class CustomHSJWTService : ICustomJWTService
    {
        private readonly JWTTokenOptions _JWTTokenOptions;
        //全局默认配置
        private readonly DefaultSettings _defaultSettings;

        /// <summary>
        /// 构造注入
        /// </summary>
        /// <param name="jwtTokenOptions"></param>
        /// <param name="defaultSettings">全局默认配置</param>
        public CustomHSJWTService(IOptionsMonitor<JWTTokenOptions> jwtTokenOptions, IOptions<DefaultSettings> defaultSettings)
        {
            _JWTTokenOptions = jwtTokenOptions.CurrentValue;
            _defaultSettings = defaultSettings.Value;
        }

        /// <summary>
        /// 生成token
        /// </summary>
        /// <param name="user">用户信息</param>
        /// <param name="expireTime">过期时间/分钟</param>
        /// <returns></returns>
        public JWTLoginResult GetToken(UsersDto user)
        {
            #region 有效载荷，爱写多少写多少；可逆过程，尽量不放敏感信息

            var claims = new[]
            {
                new Claim("ID",user.ID.ToString()),
                new Claim("UserName",user.UserName??""),
                new Claim("FullName",user.FullName??""),
                new Claim("Mobile",user.Mobile ?? ""),
                new Claim("Email",user.Email ?? ""),
                new Claim("DepartmentName",user.DepartmentName ?? ""),
                new Claim("Avatar",user.Avatar ?? ""),
                new Claim("AvatarUrl",user.AvatarUrl ?? ""),
                new Claim("Roles",user.Roles.Any()? string.Join(",", user.Roles):""),
                new Claim("RolesName",user.RolesName.Any()? string.Join(",", user.RolesName):""),
                new Claim("Permissions",user.Permissions.Any()? string.Join(",", user.Permissions):"")
            };

            //需要加密：需要加密key:
            //Nuget引入：Microsoft.IdentityModel.Tokens
            SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_JWTTokenOptions.SecurityKey));

            SigningCredentials creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            //Nuget引入：System.IdentityModel.Tokens.Jwt
            JwtSecurityToken token = new JwtSecurityToken(
             issuer: _JWTTokenOptions.Issuer,
             audience: _JWTTokenOptions.Audience, // 对象
             claims: claims, // 登录信息
             expires: DateTime.Now.AddHours(_defaultSettings.TokenExpireTime), // 过期时间
             signingCredentials: creds);

            string returnToken = new JwtSecurityTokenHandler().WriteToken(token);
            return new JWTLoginResult() { Token = returnToken };

            #endregion
        }
    }
}
